# 数据在网页源代码里面 通过链接直接请求
# 请求 95  解析 保存
import re
import threading

import requests

head_data = {
    # 字典，需要有一个键值对
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36'}


def iamge_get(url):
    html = requests.get(url, headers=head_data)

    # 数据解析
    iamge_list = re.findall('<div class="item">.*?data-original="(.*?)"', html.text, re.S)

    for i in iamge_list:
        image_url = 'https:' + i  # 是一个完整的链接
        threading.Thread(target=iamge_save, args=(image_url,)).start()


def iamge_save(image_url):
    image_data = requests.get(image_url)  # 请求图片数据

    image_name = image_url.split('/')[-1]  # 获取图片名称

    # 修改存储的路径
    image_path = 'image/' + image_name  # image/354cfeeb3e7569ae_s.jpg

    f = open(image_path, 'wb')  # 把数据保存到文件中
    f.write(image_data.content)
    f.close()

    print(image_url)


if __name__ == '__main__':

    url_1 = ['https://sc.chinaz.com/tupian/']
    url_list = url_1 + [f'https://sc.chinaz.com/tupian/index_{i}.html' for i in range(2, 6)]

    for url in url_list:
        threading.Thread(target=iamge_get, args=(url,)).start()

    # join让主线程等待子线程完成


# 97.48717427253723
# 10
